import pandas as pd
import logging
from pathlib import Path

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


def read_data(file_path):
    """读取数据并处理缺失值"""
    if not Path(file_path).is_file():
        logging.error(f"文件 {file_path} 不存在")
        return None

    try:
        data = pd.read_csv(file_path)
        # 检查并处理缺失值
        if data.isnull().values.any():
            logging.warning("数据中存在缺失值，将使用0填充")
            data.fillna(0, inplace=True)
        return data
    except Exception as e:
        logging.error(f"读取文件 {file_path} 时发生错误: {e}")
        return None


# 假设数据格式为：期号, 红球1, 红球2, ..., 红球6, 蓝球
# 示例：data.columns = ['issue', 'red_1', 'red_2', 'red_3', 'red_4', 'red_5', 'red_6', 'blue']

def frequency_analysis(data):
    """频率分析"""
    red_balls = data[['red_1', 'red_2', 'red_3', 'red_4', 'red_5', 'red_6']].values.flatten()
    blue_balls = data['blue'].values

    red_freq = pd.Series(red_balls).value_counts().sort_index()
    blue_freq = pd.Series(blue_balls).value_counts().sort_index()

    return red_freq, blue_freq


def omission_analysis(data):
    """遗漏分析"""
    all_red_balls = set(range(1, 34))
    all_blue_balls = set(range(1, 17))

    # 使用向量化操作替代逐行遍历
    red_omission = {ball: 0 for ball in all_red_balls}
    blue_omission = {ball: 0 for ball in all_blue_balls}

    for ball in all_red_balls:
        mask = ~data[['red_1', 'red_2', 'red_3', 'red_4', 'red_5', 'red_6']].isin([ball]).any(axis=1)
        red_omission[ball] = mask.sum()

    for ball in all_blue_balls:
        mask = data['blue'] != ball
        blue_omission[ball] = mask.sum()

    return pd.Series(red_omission), pd.Series(blue_omission)


def tail_distribution(data):
    """尾数分布"""
    red_tails = data[['red_1', 'red_2', 'red_3', 'red_4', 'red_5', 'red_6']].apply(lambda x: x % 10).values.flatten()
    blue_tails = data['blue'].apply(lambda x: x % 10).values

    red_tail_dist = pd.Series(red_tails).value_counts().sort_index()
    blue_tail_dist = pd.Series(blue_tails).value_counts().sort_index()

    return red_tail_dist, blue_tail_dist


def main(file_path):
    data = read_data(file_path)
    if data is None:
        return

    red_freq, blue_freq = frequency_analysis(data)
    print("红球频率：")
    print(red_freq)
    print("\n蓝球频率：")
    print(blue_freq)

    red_omission, blue_omission = omission_analysis(data)
    print("\n红球遗漏值：")
    print(red_omission.sort_values(ascending=False))
    print("\n蓝球遗漏值：")
    print(blue_omission.sort_values(ascending=False))

    red_tail_dist, blue_tail_dist = tail_distribution(data)
    print("\n红球尾数分布：")
    print(red_tail_dist)
    print("\n蓝球尾数分布：")
    print(blue_tail_dist)


if __name__ == "__main__":
    file_path = 'lottery_data.csv'  # 可以通过命令行参数传递
    main(file_path)
